package com.wiz.web.controllor;

import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.wiz.entity.Resources;
import com.wiz.entity.Roles;
import com.wiz.service.ResourcesService;
import com.wiz.service.UserService;
import com.wiz.util.Common;
import com.wiz.util.PageView;
import com.wiz.vo.ResponseJsonBody;

/**
 * 
 * @author xxy
 *
 */
@Controller
@RequestMapping(value="/resources")
public class ResourcesController {
	private transient final Logger log=LoggerFactory.getLogger(getClass());
	private Gson gson = new GsonBuilder().disableHtmlEscaping().create();
	@Autowired
	private ResourcesService resourcesService;
	
	@Autowired
	private UserService userService;
	
	/**
	 * 跳到新增页面
	 * @return
	 */
	@RequestMapping(value="addUI")
	public String addUI(Model model){
		List<Resources> resources = resourcesService.findAll();
		model.addAttribute("resources", resources);
		return "/resources/add";
	} 
	
	/**
	 * 保存新增
	 * @param model
	 * @param resources
	 * @return
	 */
	@RequestMapping(value="add")
	@ResponseBody
	public String add(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "name", required = true) String name,//角色名
			@RequestParam(value = "parentId", required = true) String parentId,
			@RequestParam(value = "resKey", required = true) String resKey,
			@RequestParam(value = "resUrl", required = true) String resUrl,//描述
			@RequestParam(value = "type", required = true) String type,//描述
			@RequestParam(value = "level", required = false) String level,//描述
			@RequestParam(value = "description", required = false) String description,//描述
			HttpSession session, Model model){
		ResponseJsonBody json = null;
		try {
			Resources resources = new Resources(0, name, Integer.valueOf(parentId),
					null, resKey, resUrl, Integer.valueOf(level),type,
					description);
			resourcesService.add(resources);
			json = new ResponseJsonBody("200", "保存成功", "sys_resc",
					"navTab", "closeCurrent", null, null);
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			json = new ResponseJsonBody("300", e.getMessage(), "sys_resc",
					"navTab", "closeCurrent", null, null);
		}
		return gson.toJson(json);
	}
	
	/**
	 * 分页查询
	 * @param model
	 * @param resources
	 * @param pageNow
	 * @return
	 */
	@RequestMapping(value="query")
	public String query(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "numPerPage", required = false,defaultValue="10") int pageSize,
			@RequestParam(value = "pageNum", required = false,defaultValue="1") int pageNow,
			@RequestParam(value = "name", required = false) String name ,//总部名称
			HttpSession session, Model model){
		PageView pageView = null;
		pageView = new PageView(pageSize, pageNow);
		Resources resources = new Resources(name);
		pageView = resourcesService.query(pageView, resources);
		model.addAttribute("pageView", pageView);
		return "/resources/list";
	}
	
	/**
	 * 根据id删除
	 * @param model
	 * @param resourcesId
	 * @return
	 */
	@RequestMapping(value="deleteById")
	@ResponseBody
	public String deleteById(Model model,String resourcesId){
		ResponseJsonBody json = null;
		try {
			resourcesService.delete(resourcesId);
			json = new ResponseJsonBody("200", "保存成功", "sys_resc",
					"", "", "", "");
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			json = new ResponseJsonBody("300", e.getMessage(), "sys_resc",
					"", "", "", "");
		}
	return gson.toJson(json);
	}
	
	/**
	 * 查询单条记录
	 * @param model
	 * @param resourcesId
	 * @param type
	 * @return
	 */
	@RequestMapping(value="getById")
	public String getById(Model model,String resourcesId,int typeKey){
		Resources resources = resourcesService.getById(resourcesId);
		model.addAttribute("resources", resources);
		List<Resources> resLists = resourcesService.findAll();
		model.addAttribute("resLists", resLists);
		if(typeKey == 1){
			return "/resources/edit";
		}else{
			return "/resources/show";
		}
	}
	
	/**
	 * 更新修改的信息
	 * @param model
	 * @param resources
	 * @return
	 */
	@RequestMapping(value="update")
	@ResponseBody
	public String updateResources(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "id", required = true) String id,//角色名
			@RequestParam(value = "name", required = true) String name,//角色名
			@RequestParam(value = "parentId", required = true) String parentId,
			@RequestParam(value = "resKey", required = true) String resKey,
			@RequestParam(value = "resUrl", required = true) String resUrl,//描述
			@RequestParam(value = "type", required = true) String type,//描述
			@RequestParam(value = "level", required = false) String level,//描述
			@RequestParam(value = "description", required = false) String description,//描述
			HttpSession session, Model model){
		ResponseJsonBody json = null;
		try {
			Resources resources = new Resources(Integer.valueOf(id), name, Integer.valueOf(parentId),
					null, resKey, resUrl, Integer.valueOf(level),type,
					description);
			resourcesService.modify(resources);
			json = new ResponseJsonBody("200", "修改成功", "sys_resc",
					"navTab", "closeCurrent", null, null);
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			json = new ResponseJsonBody("300", e.getMessage(), "sys_resc",
					"navTab", "closeCurrent", null, null);
		}
		return gson.toJson(json);
	}
	
	@RequestMapping(value="deleteAll")
	public String deleteAll(String[] check,Model model){
		for(String id : check){
			resourcesService.delete(id);
		}
		return "redirect:query.html";
	}
	/**
	 * 某个用户拥有的权限
	 * @return
	 */
	@RequestMapping(value="permissioUser")
	public String permissioUser(Model model,String userId){
		List<Resources> resources = resourcesService.getUserResources(userId);
		List<Resources> allRes = resourcesService.findAll();
		StringBuffer sb = new StringBuffer();
		sb.append("var data = [];");
		for (Resources r : allRes) {
			boolean flag = false;
			for (Resources ur : resources) {//用户拥有的权限
				if (ur.getId().equals(r.getId())) {
					sb.append("data.push({ fid: '"
							+ r.getId() + "', pfid: '"
							+ r.getParentId()
							+ "', fname: '" + r.getName()
							+ "',ischecked: true});");
					flag = true;
				}
			}
			if (!flag) {
				sb.append("data.push({ fid: '"
						+ r.getId() + "', pfid: '"
						+ r.getParentId()
						+ "', fname: '" + r.getName()
						+ "'});");

			}
		}
		Roles roles = userService.findbyUserRole(userId);
		if(roles!=null){
			model.addAttribute("roleId", roles.getId());
		}
		model.addAttribute("resources", sb);
		return "/resources/permissioUser";
	}
	/**
	 * 某个角色拥有的权限
	 * @return
	 */
	@RequestMapping(value="permissioRole")
	public String permissioRole(Model model,String roleId){
		List<Resources> resources = resourcesService.getRoleResources(roleId);
		List<Resources> allRes = resourcesService.findAll();
		StringBuffer sb = new StringBuffer();
		sb.append("var data = [];");
		for (Resources r : allRes) {
			boolean flag = false;
			for (Resources ur : resources) {//用户拥有的权限
				if (ur.getId().equals(r.getId())) {
					sb.append("data.push({ fid: '"
							+ r.getId() + "', pfid: '"
							+ r.getParentId()
							+ "', fname: '" + r.getName()
							+ "',ischecked: true});");
					flag = true;
				}
			}
			if (!flag) {
				sb.append("data.push({ fid: '"
						+ r.getId() + "', pfid: '"
						+ r.getParentId()
						+ "', fname: '" + r.getName()
						+ "'});");

			}
		}
		model.addAttribute("roleId", roleId);
		model.addAttribute("resources", sb);
		return "/resources/permissioUser";
	}
	@RequestMapping(value="saveRoleRescours")
	@ResponseBody
	public String saveRoleRescours(String roleId,String rescId){
		String errorCode = "1000";
		List<String> list = Common.removeSameItem(Arrays.asList(rescId.split(",")));
		try {
			resourcesService.saveRoleRescours(roleId, list);
		} catch (Exception e) {
			e.printStackTrace();
			errorCode="1001";
		}
		return errorCode;
	}
}
